package com.atguigu.yygh.filter;

import com.google.common.net.HttpHeaders;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

//全局过滤
//@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

//    执行过滤功能
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        Mono<Void> result = null;
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
//        放行登录接口的请求
        if (antPathMatcher.match("/admin/user/**",path)){
           return chain.filter(exchange);
        }else{
//            对于非登录接口,必须登录之后才能通过
            List<String> resultString =  request.getHeaders().get("X-Token");
            if (resultString == null){
//                拦截 :-->设置结束请求
                ServerHttpResponse response = exchange.getResponse();
                response.setStatusCode(HttpStatus.SEE_OTHER);
//                路由跳转
                response.getHeaders().set(HttpHeaders.LOCATION,"http://localhost:9528");
                result =response.setComplete();
            }else {
//                放行
               return chain.filter(exchange);
            }
        }
        return result;
    }

//    影响的是全局过滤器的执行顺序,值越小优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}
